package org.c41.net;

import java.io.IOException;
import java.net.ServerSocket;

import org.c41.system.ICloseable;
import org.c41.util.ThreadPool;

public class TCPServer implements ICloseable{

	private ServerSocket server;
	private ThreadPool pool = new ThreadPool();
	
	public TCPServer(int port) throws IOException{
		this.server=new ServerSocket(port);
	}
	
	public TCPServer() throws IOException{
		this.server=new ServerSocket();
	}
	
	public void execute(final TCPServerProcess process){
		while(!isClosed()){
			try(TCPSocket socket = new TCPSocket(server.accept());){
				pool.execute(new Runnable(){
					@Override
					public void run() {
						process.process(socket);
					}
				});
			} catch (IOException e) {
			}
		}
	}
	
	public void setMaxThreads(int num){
		pool.setMaxThreads(num);
	}
	
	public int getMaxThreads(){
		return pool.getMaxThreads();
	}
	
	@Override
	public void close() throws IOException{
		server.close();
	}

	@Override
	public boolean isClosed() {
		return server.isClosed();
	}
	
}
